<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\SignatureHelper;  //发送短信
use think\Db;
use fast\Http;
use fast\Wxsdk; //微信接口
// use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;

/**
 * 示例接口
 */
class Yuye extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];




    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/yuye/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */

   






    /**
     * 无需登录的接口
     *
     */
    public function test()
    {   dump(config('site.adminopenid'));
        exit();
        // $this->sms('19983297340','496631',1);
        dump($this->sms('oialNwX8a2rKtyecL2yuqb2uLSHQ','19983297340','QQ496631085',2));
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    private function send_wxmoban(){
        $this->Wxsdk = new Wxsdk();
    }
    //下载 微信服务上的数据 传递serverid  GET
    public function httpget_down(){
        $getData = $this->request->param();
        if(!empty($getData['serverid'])){
            $serverid = $getData['serverid'];

            $this->Wxsdk = new Wxsdk();
            $AccessToken = $this->Wxsdk->getAccessToken(); 
            $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$AccessToken.'&media_id='.$serverid;
            $fileinfo =  file_get_contents($url);
            $file = 'uploads/wechat/'.time().rand(11111,99999).'.png';

            file_put_contents($file, $fileinfo);
            $file = '/'.$file;
            return ['code'=>1,'msg'=>$file];//返回目录
            // echo('ok');

        }else{
            return ['code'=>-1,'msg'=>'没有serverid'];
        }
    }

    public function get_admin_openid_arr($openid=null){
        $site = config('site');
        $arr = array();
        foreach ($site as $key => $value) {
            if(strstr($key,'adminopenid')){
                array_push($arr,$value);
            }
        }
        if(!empty($openid)){
            array_push($arr,$openid);
        }
        return $arr;
    }
    //投诉建议提交
    public function suggestions(){
        $data['msg'] = '提交失败';
        $data['code'] = -1;

        $getData = $this->request->param();
        // $vcode = $getData['vcode']?$getData['vcode']:"";

        $openid = session('user.openid');
        $user = $this->get_openid_user($openid);
        if($user){
            // if($user['code']!=$vcode){
            //     $data['msg'] = '验证码错误';
            //     return $data;
            // }else{
                
                $db_data['proposal'] = $getData['proposal']?$getData['proposal']:"";

                $db_data['ltdname'] = $getData['ltdname']?$getData['ltdname']:"";
                $db_data['problem'] = $getData['problem']?$getData['problem']:"";
                // $db_data['content'] = $getData['content']?$getData['content']:"";
                $db_data['openid'] = $openid;


                // $tishi['name'] = '姓名';
                // $tishi['tel'] = '手机号';
                $tishi['ltdname'] = '公司名';
                $tishi['problem'] = '问题或建议';
                $tishi['proposal'] = '建议措施';
                foreach ($db_data as $key => $value) {
                    if(empty($value)){
                        $data['msg'] = $tishi[$key].'不能为空';
                        return $data;
                    }
                }
                
                // if(!$this->is_mobile($db_data['tel'])){
                //     $data['msg'] = '手机号不正确';
                //     return $data;
                // }




                // $db_data['codetime'] = time()+60;
                // $db_data['code'] = $code;
                $db_data['createtime'] = time();
                $res_insert = Db::name('suggest')->insertGetId($db_data);
                if($res_insert){

                    $data['code'] = 1;
                    $data['msg'] = '提交成功';
                    $url = 'http://yywl.wxjoi.com/index.php/index/index/jianyi/id/'.$res_insert;
                    //发送微信模板消息 给用户和管理员
                    $db_data['title'] = '投诉建议';
                    $db_data['ltdtel'] = $user['ltdtel'];
                    $db_data['tel'] = $user['tel'];
                    $db_data['name'] = $user['name'];
                    $db_data['room'] = $user['room'];
                    $this->send_messageTemplate($this->get_admin_openid_arr($openid), $db_data,$url,'jianyi');
                }

                return $data;
            // }
        }else{
            $data['msg'] = '请勿非法提交 你登陆了吗?';
        }
        return $data;
    }


    public function pingjia(){

        $data['msg'] = '提交失败';
        $data['code'] = -1;

        $getData = $this->request->param();
        if(!empty($getData['id'])) {
        	$id = $getData['id'];
        	$type = !empty($getData['type'])?$getData['type']:"1";
        	switch ($type) {
        		case '1':
        			$tabname = 'baoxiu';//报修
        			break;
        		case '2':
        			$tabname = 'suggest';//建议
        			break;
        		default:
        			$data['msg'] = "请勿非法post提交";
        			return $data;
        			break;
        	}

        	$db_status = Db::name($tabname)->where('id',$id)->find();
        	if($db_status){
        		if($db_status['status'] != 2 ){
        			$data['msg'] = "请勿非法post提交,状态未完成，暂时无法评价";
        			return $data;
        		}
        	}
        }else{
        	$data['msg'] = "请勿非法post提交";
			return $data;
        }

        $openid = session('user.openid');
        if($openid!=$db_status['openid']){
        	$data['msg'] ="评价失败，非本人评价！";
			return $data;
        }

        $user = $this->get_openid_user($openid);
        if($user){

        	$db_data['appraise'] = !empty($getData['appraise'])?$getData['appraise']:"";
        	$db_data['grade'] = !empty($getData['grade'])?$getData['grade']:"3";
        	$res = Db::name($tabname)->where('id',$id)->update($db_data);
        	if($res){
        		$data['msg'] = "评价成功";
        		$data['code'] = 1;
        	}
        }

        return $data;
        // $vcode = $getData['vcode']?$getData['vcode']:"";
    }


    //报修单提交
    public function baoxiu(){
        $data['msg'] = '提交失败';
        $data['code'] = -1;

        $getData = $this->request->param();
        // $vcode = $getData['vcode']?$getData['vcode']:"";

        $openid = session('user.openid');
        $user = $this->get_openid_user($openid);
        if($user){
            // if($user['code']!=$vcode){
            //     $data['msg'] = '验证码错误';
            //     return $data;
            // }else{
                $db_data['name'] = $getData['name']?$getData['name']:"";
                $db_data['tel'] = $getData['tel']?$getData['tel']:"";
                $db_data['ltdtel'] = $getData['ltdtel']?$getData['ltdtel']:"";
                $db_data['room'] = $getData['room']?$getData['room']:"";
                $db_data['content'] = $getData['content']?$getData['content']:"";
                $db_data['openid'] = $openid;


                $tishi['name'] = '姓名';
                $tishi['tel'] = '手机号';
                $tishi['ltdtel'] = '公司电话';
                $tishi['room'] = '房间号';
                $tishi['content'] = '内容';
                foreach ($db_data as $key => $value) {
                    if(empty($value)){
                        $data['msg'] = $tishi[$key].'不能为空';
                        return $data;
                    }
                }

                if(!$this->is_mobile($db_data['tel'])){
                    $data['msg'] = '手机号不正确';
                    return $data;
                }





                // $db_data['codetime'] = time()+60;
                // $db_data['code'] = $code;
                $db_data['images'] = !empty($getData['images'])?$getData['images']:"";
                $db_data['image'] = !empty($getData['image'])?$getData['image']:"";
                $db_data['createtime'] = time();
                $res_insert = Db::name('baoxiu')->insertGetId($db_data);
                if($res_insert){

                    $data['code'] = 1;
                    $data['msg'] = '提交成功';
                    $url = 'http://yywl.wxjoi.com/index.php/index/index/baoxiu/id/'.$res_insert;
                    //发送微信模板消息 给用户和管理员
                    $db_data['title'] = '一键报修';
                    $this->send_messageTemplate($this->get_admin_openid_arr($openid), $db_data,$url,'baoxiu');
                }

                return $data;
            // }
        }else{
            $data['msg'] = '请勿非法提交 你登陆了吗?';
        }
        return $data;
    }


    //修改用户
    public function update_user(){
        $data['msg'] = '修改失败';
        $data['code'] = -1;

        $getData = $this->request->param();
        // $vcode = $getData['vcode']?$getData['vcode']:"";

        $openid = session('user.openid');
        $user = $this->get_openid_user($openid);
        if($user){
            // if($user['code']!=$vcode){
            //     $data['msg'] = '验证码错误';
            //     return $data;
            // }else{
                $db_data['name'] = !empty($getData['name'])?$getData['name']:"";

                if(isset($getData['tel'])) $db_data['tel'] = $getData['tel'];
                $db_data['ltdname'] = !empty($getData['ltdname'])?$getData['ltdname']:"";
                $db_data['room'] = !empty($getData['room'])?$getData['room']:"";

                $tishi['name'] = '姓名';
                $tishi['tel'] = '手机号';
                $tishi['ltdname'] = '公司名称';
                $tishi['room'] = '房间号';

                foreach ($db_data as $key => $value) {
                    if(empty($value)){
                        $data['msg'] = $tishi[$key].'不能为空';
                        return $data;
                    }
                }
                if(isset($db_data['tel']))
                if(!$this->is_mobile($db_data['tel'])){
                    $data['msg'] = '手机号不正确';
                    return $data;
                }

                // $db_data['code'] = '0000';


                // $db_data['codetime'] = time()+60;
                // $db_data['code'] = $code;
                $db_data['updatetime'] = time();
                $res_update = Db::name('wxuser')->where('openid',$openid)->update($db_data);
                if($res_update){
                    $data['code'] = 1;
                    $data['msg'] = '修改成功';
                }else{
                    $data['msg'] = '你未修改任何资料';
                }

                return $data;
            // }
        }else{
            $data['msg'] = '请勿非法提交 XiaoHe QQ496631085';
        }
        return $data;
    }


    //会员注册
    public function reg_user(){
        $data['msg'] = '注册失败';
        $data['code'] = -1;

        $getData = $this->request->param();
        $vcode = $getData['vcode']?$getData['vcode']:"";

        $openid = session('user.openid');
        $user = $this->get_openid_user($openid);
        if($user){
            if($user['code']!=$vcode){
                $data['msg'] = '验证码错误';
                return $data;
            }else{
                $db_data['name'] = $getData['name']?$getData['name']:"";
                $db_data['tel'] = $getData['tel']?$getData['tel']:"";
                $db_data['ltdname'] = $getData['ltdname']?$getData['ltdname']:"";
                $db_data['room'] = $getData['room']?$getData['room']:"";

                $tishi['name'] = '姓名';
                $tishi['tel'] = '手机号';
                $tishi['ltdname'] = '公司名称';
                $tishi['room'] = '房间号';

                foreach ($db_data as $key => $value) {
                    if(empty($value)){
                        $data['msg'] = $tishi[$key].'不能为空';
                        return $data;
                    }
                }
                if(!$this->is_mobile($db_data['tel'])){
                    $data['msg'] = '手机号不正确';
                    return $data;
                }

                $db_data['code'] = '0000';


                // $db_data['codetime'] = time()+60;
                // $db_data['code'] = $code;
                $db_data['updatetime'] = time();
                $res_update = Db::name('wxuser')->where('openid',$openid)->update($db_data);
                if($res_update){
                    $data['code'] = 1;
                    $data['msg'] = '注册成功';
                }

                return $data;
            }
        }else{
            $data['msg'] = '请勿非法提交 QQ496631085';
        }
        return $data;
    }


    
    //给用户发送验证码   参数 type 类型1注册2修改   tel 手机号码
    public function send_yzm(){
        $data['msg'] = '错误';
        $data['code'] = -1;

        $tel = $this->request->param()['tel'];
        $type = $this->request->param()['type'];
        if(!$this->is_mobile($tel)){
            $data['msg'] = '请输入正确的手机号码';
            return $data;
        }

        if(empty(session('user'))){
            $data['msg'] = '请勿非法提交';
            return $data;
        }else{
            $openid = session('user.openid');
            $code = $this->get_code();
            $type = $type?$type:1;
            return $this->sms($openid,$tel,$code,$type);
        }

    }






    //发送短信     
    public function sms($openid = null,$tel="18784263545",$code = 'QQ496631085',$moban = 1)
    {   
        $data['msg'] = '错误';
        $data['code'] = -1;

        // dump(new Sms());
        if(!$openid){
            $data['msg'] = "请传openid";
            return $data;
        }
        $res_user = Db::name('wxuser')->where('openid',$openid)->find();
        if($res_user){
            if($res_user['codetime']>time()){
                $data['msg'] = $res_user['codetime']-time().'秒后再重新发送验证码';
                return $data;
            }else{
                $db_data['codetime'] = time()+60;
                $db_data['code'] = $code;
                $res_update = Db::name('wxuser')->where('openid',$openid)->update($db_data);
            }
        }
        
        $params = array ();


        // *** 需用户填写部分 ***
        // fixme 必填：是否启用https
        $security = false;

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息

        $accessKeyId = "LTAI4FmvUbkFj7S1UoSFqWRG";
        $accessKeySecret = "Rbt4LBoRDhP6aY5gDS8reqJHfxcfoT";

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $tel;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "宇野网络大厦";

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        switch ($moban) {
            case '1':
                $params["TemplateCode"] = "SMS_185595022";//注冊用戶
                break;
            case '2':
                $params["TemplateCode"] = "SMS_185595025"; //改手機號
                break;
            default:
                $params["TemplateCode"] = "SMS_185595025";
                break;
        }

        // $params["TemplateCode"] = "SMS_185595022";
                //SMS_185595025
                // 模版内容:
                // 验证码${code}，您正在进行身份验证，打死不要告诉别人哦！



        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array (
            "code" => $code
        );

        // fixme 可选: 设置发送短信流水号
        $params['OutId'] = "12345";

        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        // $params['SmsUpExtendCode'] = "1234567";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );
        // $res_data = json_decode($content,true);
        // dump((array)$content);
        $res_data = (array)$content;

        // ini_set("display_errors", "on"); // 显示错误提示，仅用于测试时排查问题
        // // error_reporting(E_ALL); // 显示所有错误提示，仅用于测试时排查问题
        // set_time_limit(0); // 防止脚本超时，仅用于测试使用，生产环境请按实际情况设置
        // header("Content-Type: text/plain; charset=utf-8"); // 输出为utf-8的文本格式，仅用于测试

        // 验证发送短信(SendSms)接口
        // print_r(sendSms());

        $data['msg'] = json_encode($res_data);
        if($res_data['Code']=="OK"){
            $data['code'] = 1;
            $data['msg'] = '发送成功';
            return $data;
        }else{
            file_put_contents("log/sms.txt", date('Y-m-d H:i:s____').$data['msg'].PHP_EOL, FILE_APPEND);
            return $data;
        }

        // $this->success($content, $this->request->param());
    }

    private function wx_publicTemplte_baoxiu($openid,$params,$re_url = 'http://yywl.wxjoi.com/index.php/index/index/about'){
        $data['msg'] = '发送失败';
        $data['code'] = -1;
        $this->Wxsdk = new Wxsdk();

        $AccessToken = $this->Wxsdk->getAccessToken(); 
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$AccessToken;

        $wx_post = ' {
               "touser":"'.$openid.'",
               "template_id":"6phJgPCq-t6tdT7UkIePzTnhJXz8jmrqnvSTbabNZdk",
               "url":"'.$re_url.'",  
                 
               "data":{
                       "first": {
                           "value":"'.$params["title"].'",
                           "color":"#173177"
                       },
                       "keyword1":{
                           "value":"房间号:'.$params['room'].'---报修人:'.$params['name'].'",
                           "color":"#123177"
                       },
                       "keyword2": {
                           "value":"'.date("Y-m-d H:i:s").'",
                           "color":"#103170"
                       },
                       "keyword3": {
                           "value":"'.$params["content"].'",
                           "color":"#173007"
                       },
                       "remark":{
                           "value":"宇野网络大厦",
                           "color":"#173177"
                       }
               }
           }';

        
        $res_code = json_decode(Http::post($url,$wx_post),true);

        switch ($res_code['errcode']) {
            case '0':
                $data['msg'] = '发送成功';
                $data['code'] = 1;
                break;
            
            default:
                $data['msg'] = $res_code;
                break;
        }
        return $data;
    }




    private function wx_publicTemplte_jianyi($openid,$params,$re_url = 'http://yywl.wxjoi.com/index.php/index/index/about'){
        $data['msg'] = '发送失败';
        $data['code'] = -1;
        $this->Wxsdk = new Wxsdk();

        $AccessToken = $this->Wxsdk->getAccessToken(); 
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$AccessToken;

        $wx_post = ' {
               "touser":"'.$openid.'",
               "template_id":"6phJgPCq-t6tdT7UkIePzTnhJXz8jmrqnvSTbabNZdk",
               "url":"'.$re_url.'",  
                 
               "data":{
                       "first": {
                           "value":"'.$params["title"].'",
                           "color":"#173177"
                       },
                       "keyword1":{
                           "value":"房间号:'.$params['room'].'---姓名:'.$params['name'].'",
                           "color":"#123177"
                       },
                       "keyword2": {
                           "value":"'.date("Y-m-d H:i:s").'",
                           "color":"#103170"
                       },
                       "keyword3": {
                           "value":"问题:'.$params['problem'].'",
                           "color":"#173007"
                       },
                       "remark":{
                           "value":"'.$params["proposal"].'",
                           "color":"#173177"
                       }
               }
           }';

        
        $res_code = json_decode(Http::post($url,$wx_post),true);

        switch ($res_code['errcode']) {
            case '0':
                $data['msg'] = '发送成功';
                $data['code'] = 1;
                break;
            
            default:
                $data['msg'] = $res_code;
                break;
        }
        return $data;
    }


    //
    public function send_messageTemplate($openid_data,$params,$url = 'http://yywl.wxjoi.com/index.php/index/index/about',$moban='baoxiu'){
        if(!is_array($openid_data)){
            $openid = $openid_data;
            if($moban=='baoxiu'){
                $data = $this->wx_publicTemplte_baoxiu($openid,$params,$url);
            }else{
                $data = $this->wx_publicTemplte_jianyi($openid,$params,$url);
            }
            
               

        }else{
            $he = 0;
            $data['msg'] = '发送失败';
           foreach($openid_data as $openid){
                 

                if($moban=='baoxiu'){
                    $res_code = $this->wx_publicTemplte_baoxiu($openid,$params,$url);
                }else{
                    $res_code = $this->wx_publicTemplte_jianyi($openid,$params,$url);
                }

              if(!$res_code['code']){
                $he--;
                 $data['msg'] = $data['msg'].json_encode($res_code['msg']);
              } 

           }
           if($he){
                $data['msg'] = '发送成功';
                $data['code'] = sizeof($openid_data);
           }else{
                
                $data['code'] = $he;
           }

           
           
        }
        return $data;

    }

    //验证码的位数
    public function get_code($wei = 4){
        switch ($wei) {
            case '4':
                $code = rand(1000, 9999);
                break;
            case '6':
                $code = rand(100000, 999999);
                break;
            
            default:
                $code = rand(100000, 999999);
                break;
        }
        return $code;
    }


        //验证手机号码
    public function is_mobile($phonenumber) {
             if(preg_match("/^1[345789]{1}\d{9}$/",$phonenumber)){  
                 return true; 
             }else{  
                 return false; 
            }  
    }

    private function get_openid_user($openid){
        $data = Db::name('wxuser')->where('openid',$openid)->find();
        return $data;
    }







}
